<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\ygzc\model;



use think\db\Query;
use think\Model;
use tree\Tree;
use app\common\logic\Config;

class GoodsCategoryModel extends Model
{
	
    protected $name = 'goods_category';
	
	protected $type = [
        'more' => 'array',
    ];
	
    /**
     * 生成分类 select树形结构
     * @param int $selectId   需要选中的分类 id
     * @param int $currentCid 需要隐藏的分类 id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function CategoryTree($selectId = 0, $currentCid = 0)
    {
        $categories = $this->order("list_order ASC")
            ->where('delete_time', 0)
            ->where(function (Query $query) use ($currentCid) {
                if (!empty($currentCid)) {
                    $query->where('id', 'neq', $currentCid);
                }
            })
            ->select()->toArray();

        $tree       = new Tree();
      
        $newCategories = [];
        foreach ($categories as $item) {
            array_push($newCategories, $item);
        }
        $tree->init($newCategories);
        $treeStr = $tree->getTreeArray(0);

        return $treeStr;
    }
	
	public function adminCategoryTree($selectId = 0, $currentCid = 0)
    {
        $categories = $this->order("list_order ASC")
            ->where('delete_time', 0)
            ->where(function (Query $query) use ($currentCid) {
                if (!empty($currentCid)) {
                    $query->where('id', 'neq', $currentCid);
                }
            })
            ->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        $newCategories = [];
        foreach ($categories as $item) {
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";
            array_push($newCategories, $item);
        }
        $tree->init($newCategories);
        $str     = '<option value=\"{$id}\" {$selected}>{$spacer}{$name}</option>';
        $treeStr = $tree->getTree(0,$str);

        return $treeStr;
    }

    /**
     * 分类树形结构
     * @param int    $currentIds
     * @param string $tpl
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminCategoryTableTree($currentIds = 0, $tpl = '')
    {
        $where['delete_time'] = 0;
        $categories = $this->order("id ASC")->where($where)->select()->toArray();
        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }

        $newCategories = [];
        foreach ($categories as $item) {

            $item['parent_id_node'] = ($item['parent_id']) ? ' class="child-of-node-' . $item['parent_id'] . '"' : '';
            $item['style']          = empty($item['parent_id']) ? '' : '';
            $item['status_text']    = empty($item['status']) ? '<span class="label label-warning">隐藏</span>' : '<span class="label label-success">显示</span>';
            $item['checked']        = in_array($item['id'], $currentIds) ? "checked" : "";
            //$item['url']            = cmf_url('portal/List/index', ['id' => $item['id']]);
            $add = '';
            if(empty($item['parent_id'])){
                $add = ' <a class="layui-btn layui-btn-sm layui-btn-normal" href="' . url("goods/add_category", ["id" => $item['id']]) . '">添加子分类</a>';
            }
            $parents = $this->where('id',$item['parent_id'])->find();
            $three = [];
            if(!empty($parents['parent_id'])){
                $three = $this->where('id',$parents['parent_id'])->find();
            }
            if(empty($three)){
                $add = ' <a class="layui-btn layui-btn-sm layui-btn-normal" href="' . url("goods/add_category", ["id" => $item['id']]) . '">添加子分类</a>';
            }
			
            $item['str_action']     = $add.' <a class="layui-btn layui-btn-sm" href="' . url("goods/edit_category", ["id" => $item['id']]) . '">' . lang('EDIT') . '</a>  <button class="layui-btn layui-btn-sm layui-btn-danger" onclick="del('.$item["id"].')">' . lang('DELETE') . '</button> ';
            if (!empty($item['status'])) {
                $item['str_action'] .= '<button class="layui-btn layui-btn-sm layui-btn-warm" onclick="set('.$item["id"].',0)">隐藏</button>';
            } else {
                $item['str_action'] .= '<button class="layui-btn layui-btn-sm layui-btn-warm" onclick="set('.$item["id"].',1)">显示</button>';
            }
			if ($item['isrecommand']==1) {
                $item['str_action'] .= '<button class="layui-btn layui-btn-sm " onclick="setr('.$item["id"].',0)">取消推荐</button>';
            } else {
                $item['str_action'] .= '<button class="layui-btn layui-btn-sm " onclick="setr('.$item["id"].',1)">推荐</button>';
            }
            array_push($newCategories, $item);
        }
        $tree->init($newCategories);

        if (empty($tpl)) {
            $tpl = " <tr id='node-\$id' \$parent_id_node style='\$style' data-parent_id='\$parent_id' data-id='\$id'>
                        <td>\$id</td>
                        <td>\$spacer <a >\$name</a></td>

                        <td>\$str_action</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);
        //var_dump($treeStr);
        return $treeStr;
    }

    /**
     * 添加文章分类
     * @param $data
     * @return bool
     */
    public function addCategory($data)
    {

        $result = true;
        self::startTrans();
        try {
            
            if (!empty($data['more']['thumbnail']) && strpos($data['more']['thumbnail'], "http") === false) {
                $Config = new Config();
                $Config->getQiniuyun();//七牛云配置
                $data['more']['thumbnail'] = CONFIG_QINIUYUAN_PROTOCOL.CONFIG_QINIUYUAN_DOMAIN.$data['more']['thumbnail'];
            }

            $this->allowField(true)->save($data);
            $id = $this->id;
            if (empty($data['parent_id'])) {

                $this->where('id', $id)->update(['path' => '0-' . $id]);
            } else {
                $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
                $this->where('id', $id)->update(['path' => "$parentPath-$id"]);

            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            $result = false;
        }

        if ($result != false) {
            //设置别名
            $routeModel = new RouteModel();
            if (!empty($data['alias']) && !empty($id)) {
                $routeModel->setRoute($data['alias'], 'portal/List/index', ['id' => $id], 2, 5000);
                $routeModel->setRoute($data['alias'] . '/:id', 'portal/Article/index', ['cid' => $id], 2, 4999);
            }
            $routeModel->getRoutes(true);
        }

        return $result;
    }

    public function editCategory($data)
    {
        $result = true;

        $id          = intval($data['id']);
        $parentId    = intval($data['parent_id']);
        $oldCategory = $this->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath-$id";
            }
        }

        if (empty($oldCategory) || empty($newPath)) {
            $result = false;
        } else {

            $data['path'] = $newPath;
            if (!empty($data['more']['thumbnail']) && strpos($data['more']['thumbnail'], "http") === false) {
                $Config = new Config();
                $Config->getQiniuyun();//七牛云配置
                $data['more']['thumbnail'] = CONFIG_QINIUYUAN_PROTOCOL.CONFIG_QINIUYUAN_DOMAIN.$data['more']['thumbnail'];
            }
            
            $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

            $children = $this->field('id,path')->where('path', 'like', $oldCategory['path'] . "-%")->select();
            if (!$children->isEmpty()) {
                foreach ($children as $child) {
                    $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
                    $this->where('id', $child['id'])->update(['path' => $childPath], ['id' => $child['id']]);
                }
            }

            $routeModel = new RouteModel();
            if (!empty($data['alias'])) {
                $routeModel->setRoute($data['alias'], 'portal/List/index', ['id' => $data['id']], 2, 5000);
                $routeModel->setRoute($data['alias'] . '/:id', 'portal/Article/index', ['cid' => $data['id']], 2, 4999);
            } else {
                $routeModel->deleteRoute('portal/List/index', ['id' => $data['id']]);
                $routeModel->deleteRoute('portal/Article/index', ['cid' => $data['id']]);
            }

            $routeModel->getRoutes(true);
        }


        return $result;
    }


    //获取全部分类
    public function getCategory(){
        $one = $this->where(['parent_id'=>0,'status'=>1])->select()->toArray();
        return $this->for_data($one);
    }

    public function for_data($data){
        foreach($data as $k=>$value){
            $two = $this->where(['parent_id'=>$value['id'],'status'=>1])->select()->toArray();
            if(!empty($two)){
                foreach($two as $k1=>$v1){
                    $three = $this->where(['parent_id'=>$v1['id'],'status'=>1])->select()->toArray();
                    $two[$k1]['child'] = $three;
                }
                $data[$k]['child'] = $two;
            }else{
                $two[$k]['child'] = [];
            }
            //
        }
        return $data;
    }

    //按照条件搜索分类
    public function get_category($param,$field){
        $data = $this->where($param)->field($field)->order('list_order asc')->select()->toArray();
        foreach($data as $k=>$value){
            if(!empty($value['thumb'])){
                $data[$k]['thumb'] = 'https://'.$_SERVER['HTTP_HOST'].$value['thumb'];
            }
        }
        return $data;
    }

}